import { Request, Response, NextFunction } from "express";
import mongoose from "mongoose";
import { MongoServerError, MongoError } from "mongodb";

interface ErrorResponse {
  statusCode: number;
  error: string;
  message: string;
  details?: Record<string, any>;
}

export function mongooseErrorHandler(
  err: any,
  req: Request,
  res: Response<ErrorResponse>,
  next: NextFunction
) {
  if (err instanceof mongoose.Error) {
    let statusCode = 400;
    let message = err.message;
    let error = err.name;
    let details: Record<string, any> | undefined;

    if (err instanceof mongoose.Error.ValidationError) {
      message = "Validation failed";
      details = {};
      for (const key in err.errors) {
        if (Object.prototype.hasOwnProperty.call(err.errors, key)) {
          details[key] = err.errors[key]?.message;
        }
      }
    }

    if (err instanceof mongoose.Error.CastError) {
      message = `Invalid value for field "${err.path}"`;
    }

    return res.status(statusCode).json({
      statusCode,
      error,
      message,
      ...(details && { details }),
    });
  }

  // 不是 mongoose 错误，继续往后传
  next(err);
}
